package com.freewater.springboot.demo.dataaccess.oxm.xstream;

import com.freewater.springboot.demo.PackageUtils;
import lombok.Getter;
import lombok.Setter;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

@Setter
@Getter
public class Application {
    private static final String FILE_NAME = "settings.xml";
    private Settings settings = new Settings();
    private Marshaller marshaller;
    private Unmarshaller unmarshaller;

    public void saveSettings() throws IOException {
        try (FileOutputStream os = new FileOutputStream(getFile())) {
            this.marshaller.marshal(settings, new StreamResult(os));
        }
    }

    public void loadSettings() throws IOException {
        try (FileInputStream is = new FileInputStream(getFile())) {
            this.settings = (Settings) this.unmarshaller.unmarshal(new StreamSource(is));
        }
    }

    private File getFile() {
        String classPath = PackageUtils.getClassPathFroClass(Main.class) + "/" + FILE_NAME;
        ClassPathResource classPathResource = new ClassPathResource(classPath);
        try {
            return classPathResource.getFile();
        } catch (IOException e) {
            throw new RuntimeException("未找到文件");
        }
    }
}
